package db

import (
	"distributed/conf"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
	"log"
	"net/url"
	"os"
	"time"
)

var DB *gorm.DB

func DBConnect() {
	var (
		dbHost = conf.GetConfig("db_host")
		dbPort = conf.GetConfig("db_port")
		dbUser = conf.GetConfig("db_user")
		dbPass = conf.GetConfig("db_pass")
		dbName = conf.GetConfig("db_name")
	)
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&loc=%s&parseTime=true",
		dbUser,
		dbPass,
		dbHost,
		dbPort,
		dbName,
		url.QueryEscape("Asia/Shanghai"))

	var err error

	DB, err = gorm.Open("mysql", dsn)
	if err != nil {
		log.Print("database connect error:", err)
		os.Exit(0)
	}
	DB.SingularTable(true)
	DB.DB().SetMaxOpenConns(200)
	DB.DB().SetMaxIdleConns(20)
	DB.DB().SetConnMaxLifetime(1 * time.Second)
	DB = DB.Debug()

	DB.Set("gorm:table_options", "ENGINE=InnoDB").
		AutoMigrate(
			//&Record{},
			&BriefInformationHackPai{},
			//&BriefInformationNet163{},
			//&BriefInformationNet163News{},
			&PlayList{},
			&Comment{},
			&Song{},
		)
	log.Print("database connect success")
}
